<template>
    <div style="border:1px solid rgba(0,0,0,.1)">
        <Toolbar :editor="editor" v-if="!preview"></Toolbar>
        <Editor @onCreated="createEditor" :mode="'simple'" @onChange="editorChange" :style="{
            minHeight: '330px'
        }" :defaultConfig="{
            readOnly:preview,
            MENU_CONF: {
                uploadImage: {
                    server: '/admin/ajax/upload',
                    fieldName: 'file',
                    maxFileSize: 1024 * 1024 * 4,
                    headers: {
                        batoken: this.$store.state.token
                    },
                    customInsert: this.customInsert
                }
            },
            placeholder: '请输入项目详情',
            autoFouces: false,
            scroll: true,
        }"></Editor>
    </div>
</template>
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
    data() {
        return {
            editor: null
        }
    },
    components: {
        Editor, Toolbar
    },
    props: {
        value: String,
        preview:Boolean
    },
    watch: {
        value: {
            handler(value) {
                this.setHtml(value)
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        setHtml(value) {
            this.$nextTick(() => {
                if (this.editor) {
                    this.editor.setHtml(value)
                } else {
                    this.setHtml(value)
                }
            })
        },
        createEditor(editor) {
            this.editor = Object.seal(editor)
        },
        // 监听editor改变
        editorChange() {
            if(this.editor){
                this.$emit('input', this.editor.getHtml())
            }
        },
        // Editor自定义插入图片
        customInsert(res, insertFn) {
            let file = res.data.file
            let fileUrl = "https://zdcloud.zxkjnc.com"
            insertFn(fileUrl + file.url, file.name, fileUrl + file.url)
        },
    }
}
</script>
<style>
@import '@wangeditor/editor/dist/css/style.css';
</style>